import {} from 'cloud'
import {
  ui
} from './ui'

const db = wx.cloud.database()

export const dsx = {
  coll: function (dsName) {
    return db.collection(dsName)
  },
  cmd: db.command,
  checkTrue(value) {
    if (value == undefined) return undefined
    return value != undefined && value != "false" && value != false
  },
  update: function (dsName, id, data) {
    const that = this
    data = this.clone(data)
    data._id = undefined
    data._openid = undefined
    if (id) {
      return that.coll(dsName).doc(id).update({
        data: data
      })
    } else {
      return that.coll(dsName).add({
        data: data
      })
    }
  },
  remove: function (dsName, where) {
    return this.coll(dsName).where(where).remove()
  },
  cloudUpdate(dsName, id, data) {
    data = this.clone(data)
    data._id = undefined
    return wx.cloud.callFunction({
      name: 'dsUpdate',
      data: {
        _id: id,
        dsName: dsName,
        data: data
      }
    })
  },
  /**
   * @param {*} where '_openid: true' 执行时补全_openid
   */
  cloudUpdateWhere(dsName, where, data) {
    data = this.clone(data)
    data._id = undefined
    data._openid = undefined
    return wx.cloud.callFunction({
      name: 'dsUpdateWhere',
      data: {
        dsName: dsName,
        where: where,
        data: data
      }
    })
  },
  cloudUpdateByIds(dsName, ids, where, data) {
    data = this.clone(data)
    data._id = undefined
    data._openid = undefined
    return wx.cloud.callFunction({
      name: 'dsUpdateWhere',
      data: {
        dsName: dsName,
        ids,
        where: where,
        data: data
      }
    })
  },
  cloudRemove: function (dsName, where) {
    return wx.cloud.callFunction({
      name: 'dsRemove',
      data: {
        dsName: dsName,
        where: where
      }
    })
  },
  cloudGetWhere(dsName, where) {
    return wx.cloud.callFunction({
      name: 'dsGet',
      data: {
        dsName: dsName,
        where
      }
    })
  },
  cloudGetByOpenid(dsName) {
    return this.cloudGetWhere(dsName, {
      _openid: true
    })
  },
  clone(obj) {
    const objStr = JSON.stringify(obj)
    return JSON.parse(objStr)
  },
  getAll(dsName, where, field) {
    return new Promise(async (resolve, reject) => {
      const totalRes = await db.collection(dsName)
        .where(where)
        .count()
      // console.log(totalRes)
      const total = totalRes.total,
        limitNum = 20
      const times = Math.ceil(total / limitNum)
      let resArr = []
      for (let i = 0; i < times; ++i) {
        const coll = db.collection(dsName)
        const res = await (() => field ? coll.field(field) : coll)()
          .where(where)
          .skip(i * limitNum)
          .limit(limitNum)
          .get()
        resArr = resArr.concat(res.data)
      }
      resolve(resArr);
    });
  }
}